
/**
 * Module dependencies.
 */

var express = require('express')
  , cons = require('consolidate')
  , swig = require('swig')
  , http = require('http')
  , socket = require('socket.io')
  , path = require('path')
  , util = require('util')
  , connect = require('connect')
  , passport = require('passport')
  , urls = require('./server/urls')
  , sockets = require('./server/sockets')
  , signup = require('./server/signup')
  , models = require('./server/db/models')
  , modelFormat = require('./server/db/modelFormat')
  , filters = require('./server/myFilters')
  , flash = require('connect-flash');

var env = process.env.NODE_ENV;

console.log(util.format("Starting in %s mode", env));

var app = express();

app.configure(function(){
  app.set('port', process.env.PORT || 3000);
  swig.init({
      root: __dirname + '/views',
      cache: env == 'prod',
      allowErrors: true, // allows errors to be thrown and caught by express instead of suppressed
      filters: filters,
      autoescape: false
  });
  app.set('views', __dirname + '/views');
  app.engine('.html', cons.swig);
  app.set('view engine', 'html');
  app.use(express.favicon());
  app.use(express.logger('dev'));
  app.use(express.bodyParser());
  app.use(express.methodOverride());
  app.use(express.cookieParser());
  var MemoryStore = connect.session.MemoryStore;
  app.use(express.session({
    secret : "9asdg0o8y4p8w398er89wepoijh",
    store : new MemoryStore({
      reapInterval : 60000 * 10
    })
  }));
  app.use(flash());
  app.use(passport.initialize());
  app.use(passport.session());
  app.use(express.csrf());
  app.use(express.static(path.join(__dirname, 'public')));
});

app.configure('development', function(){
  app.use(express.errorHandler());
});

var server = http.createServer(app);
var io = socket.listen(server);
io.set('log level', 1);

server.listen(app.get('port'), function(){
  console.log(server.address());
  console.log("Express server listening on port " + app.get('port'));
});

passport.serializeUser(function(user, done) {
  console.log("serialized: " + user.remoteId);
  done(null, user.id);
});

passport.deserializeUser(function(id, done) {
  console.log("deserialized: " + id);
  models.Player.find(id, function (err, found) {
    done(null, found);
  });
});

modelFormat.init(models);
signup.initSignups(env, models);

urls.route(app, models, io);
sockets.handle(io, models);